package com.shop.api;

import com.alibaba.fastjson.JSON;
import com.shop.po.KuaiDi;
import com.shop.po.KuaiDi100R;
import com.shop.po.R;
import com.shop.user.service.KuaiDiService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author banxia
 * @since 2023-04-02
 */
@RestController
@RequestMapping("/kuaiDi")
@CrossOrigin
public class KuaiDiController {

    @Autowired
    private KuaiDiService service;

    //添加
    @PostMapping("/add")
    public R add(@RequestBody KuaiDi kuaiDi){
        boolean save = service.save(kuaiDi);
        if (save) {
            return R.ok();
        }else{
            return R.error("失败");
        }
    }

    //根据订单号查询
    @GetMapping("/getByOrderId/{id}")
    public R getByOrderId(@PathVariable("id") Long id){
        return R.ok().data("kd",service.getByOrderId(id));
    }


    //根据快递单号查询物流信息
    @GetMapping("/test/{type}/{id}")
    public R test(
            @PathVariable("type")String type,
            @PathVariable("id") String id){
        String json="";
        try {
            String url = "https://www.kuaidi100.com/query?type="+type+"&postid="+id;
            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();
            con.setRequestMethod("GET");
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer response = new StringBuffer();

            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            json=response.toString();
        } catch (Exception e) {
            System.out.println(e);
        }
        KuaiDi100R kuaiDi100R = JSON.parseObject(json, KuaiDi100R.class);
        System.out.println("kuaiDi100R = " + kuaiDi100R);
        return R.ok().data("res",kuaiDi100R);
    }


}

